package fr.emse.tatiana.graphical;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.SWTGraphics;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editparts.LayerManager;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorPart;

import fr.emse.tatiana.replayable.IGraphicalEditor;

public class ExportToImageAction extends Action {

	IGraphicalEditor editor;
	int type;

	public ExportToImageAction(int type, String label) {
		setText(label);
		this.type = type;
		// The id is used to refer to the action in a menu or toolbar
		//setId(ICommandIds.CMD_EXPORT);
		// Associate the action with a pre-defined command, to allow key bindings.
		//setActionDefinitionId(ICommandIds.CMD_FILTER);
		//setImageDescriptor(fr.emse.tatiana.Activator.getImageDescriptor("/icons/sample2.gif"));
		this.setEnabled(false);
	}

	public void setEditor(IEditorPart editor) {
		if (editor != null && (editor instanceof IGraphicalEditor)) {
			this.editor = (IGraphicalEditor) editor;
		} else {
			this.editor = null;
		}

		setEnabled(editor != null);
	}
	
	/**
	 * Returns the bytes of an encoded image for the specified
	 * IFigure in the specified format.
	 *
	 * @param figure the Figure to create an image for.
	 * @param format one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE, SWT.IMAGE_GIF
	 *          SWT.IMAGE_ICO, SWT.IMAGE_JPEG, or SWT.IMAGE_PNG
	 * @return the bytes of an encoded image for the specified Figure
	 */
	public byte[] createImage(GraphicalViewer viewer,int format) {

		LayerManager lm = (LayerManager)viewer.getEditPartRegistry().get(LayerManager.ID);
		IFigure figure = lm.getLayer(LayerConstants.PRINTABLE_LAYERS);

	    Device device = viewer.getControl().getDisplay();
	    Rectangle r = figure.getBounds();


	    ByteArrayOutputStream result = new ByteArrayOutputStream();


	    Image image = null;
	    GC gc = null;
	    Graphics g = null;
	    try {
	        image = new Image(device, r.width, r.height);
	        gc = new GC(image);
	        g = new SWTGraphics(gc);
	        g.translate(r.x * -1, r.y * -1);


	        figure.paint(g);


	        ImageLoader imageLoader = new ImageLoader();
	        imageLoader.data = new ImageData[] {image.getImageData()};
	        imageLoader.save(result, format);
	    } finally {
	        if (g != null) {
	            g.dispose();
	        }
	        if (gc != null) {
	            gc.dispose();
	        }
	        if (image != null) {
	            image.dispose();
	        }
	    }
	    return result.toByteArray();

	}

	@Override
	public void run() {


		if (editor != null) {
			FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); 
			String path = dialog.open();
			if (path == null) {
				return;
			}

			OutputStream out;
			try {
				out = new FileOutputStream(new File(path));
				out.write(createImage(editor.getViewer(),type));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			



		}
	}
}

